<template>
  <div class="dataSource">
    <el-divider content-position="left">
      <i></i>数据来源
    </el-divider>
    <div class="tableBox">
      <div class="btnAddBox">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="innerVisible=true">选择接口数据源</el-button>
      </div>
      <!-- v-model="selectionRow" -->
      <znxd-list ref="table" :column="columnInterface" :tableData="interfaceData" @handleCurrentChange="handleCurrentChange"></znxd-list>
    </div>
    <el-divider content-position="left">
      <i></i>接口结果字段
    </el-divider>

    <div class="tableBox">
      <znxd-list-modify v-model="currentData" :formColumn="columnKeys" :initData="tableData"></znxd-list-modify>
    </div>

    <el-dialog title="选择" :visible.sync="innerVisible " width="70%">
      <el-scrollbar wrapClass="scrollbar-wrapper">
        <interface-list-choose :v-model="chooseObj" @handelChoose="handelChoose" @close="close"></interface-list-choose>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>
<script>
import { deepCopy } from "@/utils/data.js";
// import { getDictionSelf } from "@/utils/config.js";

import { call } from "@/api/task/interface.js";


import interfaceListChoose from "../../dataSet/interface/interfaceListChoose"

export default {
  components: {
    interfaceListChoose
  },
  data() {
    return {
      // 接口列表
      interfaceData: [],
      currentInterface: {},
      columnInterface: [
        // {
        //   align: "left",
        //   name: "datasourceName",
        //   label: "数据源名称",
        //   showOverflowTooltip: true
        // },
        // {
        //   align: "left",
        //   name: "interfaceUrl",
        //   label: "URL"
        //   // showOverflowTooltip: true
        // },
        // {
        //   align: "left",
        //   name: "datasourceDesc",
        //   label: "描述"
        // },
        // {
        //   align: "center",
        //   label: "操作",
        //   width: 120,
        //   buttons: [
        //     {
        //       label: "删除",
        //       type: "warning",
        //       plain: false,
        //       size: "mini",
        //       handelClick: (row) => {
        //         this.deleteEvent(row);
        //       }
        //     }
        //   ]
        // }
      ],
      // 选择接口
      innerVisible: false,
      chooseObj: {},
      // 字段列表配置
      tableData: [],
      selectionRow: null,
      columnKeys: [
        {
          name: "columnName",
          label: "字段名称",
          type: "input"
        },
        // {
        //   name: "columnAliasName",
        //   label: "字段别名",
        //   type: "input"
        // },
        {
          name: "columnMemo",
          label: "字段别名",
          type: "input"
        },
        {
          name: "columnType",
          label: "字段类型",
          type: "input"
        },
        {
          name: "columnLong",
          label: "字段长度",
          type: "input"
        }
      ],
      currentData: []
    };
  },
  props: {
    initData: Object,
    mode: String
  },
  watch: {
    interfaceData: {
      deep: true,
      handler: function (val) {
        console.log("interfaceData 999", val);
        this.$emit("input", val);
      }
    },
    initData: {
      deep: true,
      handler: function (val) {
        if (val.readerDataSource) {
          // this.interfaceData = [];
          // this.interfaceData = [...val.readerDataSource];
          this.interfaceData = deepCopy(val.readerDataSource)
          if (this.interfaceData.length > 0) { this.$refs.table.setCurrent(this.interfaceData[0]); }
          // val.readerDataSource.map(x => {
          //   this.interfaceData.push({ ...x });
          // })
        }
        console.log("initData 1", val);
      }
    },
    // 选择触发操作
    // selectionRow(val) {
    //   console.log("selectionRow", val);
    //   this.tableData = [];
    //   let obj = {
    //     id: val.id
    //   }
    //   call(obj).then((res) => {
    //     let data = res.data;
    //     if (data.success) {
    //       console.log(res);
    //       let keys = data.data.keys;
    //       keys.map(x => {
    //         let obj = {
    //           columnName: x
    //         }
    //         this.tableData.push(obj);
    //       })
    //     } else {
    //       this.$message({
    //         message: data.msg,
    //         type: "error"
    //       });
    //     }
    //   });
    // },
    // 编辑实时保存到本地
    currentData: {
      deep: true,
      handler: function (val) {
        let _this = this;
        if (val.length > 0) {
          // console.log("this.interfaceData 8", this.interfaceData);
          // console.log("currentData 8", val);
          // console.log("this.selectionRow 8", this.selectionRow);
          this.interfaceData.map((x, index) => {
            if (x.id === this.selectionRow.id) {
              // x.interfaceResults = val;
              _this.$set(this.interfaceData[index], "interfaceResults", val)
            }
          })
          // console.log("interfaceData 2", this.interfaceData);
        }
      }
    }
  },
  methods: {
    initColumn() {
      let _this = this;
      this.columnInterface = [
        {
          align: "left",
          name: "datasourceName", // "dataSourceName", // datasourceName
          label: "数据源名称",
          showOverflowTooltip: true
        },
        {
          align: "left",
          name: "interfaceUrl", // "jobUrl", // interfaceUrl
          label: "URL"
          // showOverflowTooltip: true
        },
        // {
        //   align: "left",
        //   name: "datasourceDesc",
        //   label: "描述"
        // },
        {
          align: "center",
          label: "操作",
          width: 120,
          buttons: [
            {
              label: "删除",
              type: "warning",
              plain: false,
              size: "mini",
              handelClick: (row) => {
                _this.deleteEvent(row);
              }
            }
          ]
        }
      ]
    },
    // 校验数据
    validateForm() {
      let flag = true;

      if (!this.interfaceData || this.interfaceData.length === 0) {
        flag = false;
        this.$message({
          message: "数据源不能为空",
          type: "error"
        });
        return flag;
      }

      if (this.interfaceData && this.interfaceData.length > 0) {
        let dataFilter = this.interfaceData.filter(x => {
          return (!x.interfaceResults || x.interfaceResults.length === 0);
        })
        if (dataFilter && dataFilter.length > 0) {
          flag = false;
          this.$message({
            message: "接口结果字段不能为空",
            type: "error"
          });
        }
        return flag;
      }


      // this.$refs.form.validate((valid) => {
      //   if (valid) {
      //     flag = true;
      //   } else {
      //     flag = false;
      //   }
      // });

      return flag;
    },
    handelChoose(row) {
      let obj = Object.assign({}, row);
      // obj.dataSourceName = row.datasourceName;
      // obj.jobUrl = row.interfaceUrl;

      let isHave = this.interfaceData.filter(x => {
        return x.id === row.id;
      }).length > 0;
      if (!isHave) {
        let { id, datasourceName, interfaceUrl, requestParams } = obj
        this.interfaceData.push({ id, datasourceName, interfaceUrl, requestParams });
      }
      // console.log("row", row);
      // console.log("this.interfaceData", this.interfaceData);

      // console.log("interfaceData 3", this.interfaceData);

      this.close();
    },
    close() {
      this.innerVisible = false;
    },
    // 二级操作
    deleteEvent(row) {
      this.$confirm("确认删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // console.log("row", row);
          this.interfaceData.map((x, index) => {
            if (x.id === row.id) {
              this.interfaceData.splice(index, 1);
              // console.log("interfaceData 4", this.interfaceData);
              if (this.interfaceData.length === 0) {
                this.tableData = [];
              } else if (index === 0) {
                this.$refs.table.setCurrent(this.interfaceData[0]);
              } else {
                this.$refs.table.setCurrent(this.interfaceData[index - 1]);
              }
            }
          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "操作失败"
          });
        });
    },
    handleCurrentChange(row) {
      // console.log("selectionRow", row);
      if (!row) { return; }
      this.selectionRow = row;
      this.tableData = [];
      let obj = {
        id: row.id
      }
      console.log("this.interfaceData 8", this.interfaceData);
      let initArray = this.interfaceData.filter(x => {
        return x.id === row.id;
      })
      console.log("initArray 8", initArray);
      call(obj).then((res) => {
        let data = res.data;
        if (data.success) {
          // console.log(res);
          let keys = data.data.keys;
          // debugger
          keys.map(x => {
            let filedInfo;
            if (initArray.length > 0) {
              let initObj = initArray[0];
              let result = initObj.interfaceResults;
              if (result) {
                let fileds = result.filter(r => {
                  return r.dataResourceFieldName === x;
                })
                // debugger
                if (fileds.length > 0) {
                  filedInfo = fileds[0];
                }
              }
            }
            let obj = {
            }
            if (filedInfo) {
              // console.log(1, filedInfo);
              obj = {
                ...filedInfo
                // columnName: x
              }
            } else {
              obj = {
                columnName: x,
                dataResourceFieldName: x,
                columnMemo: x,
                columnType: "varchar",
                columnLong: "255"
              }
            }
            // debugger
            this.tableData.push(obj);
          })
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          });
        }
      });
    }
  },
  mounted() {
    this.initColumn();
    // if (this.initData.readerColumns) { this.initSelection = [...this.initData.readerColumns]; }
    // this.setRules();
  }
};
</script>
<style lang="scss" scoped>
.dataSource {
  .el-divider__text.is-left {
    left: 0;
    display: flex;
    flex-direction: row;
    > i {
      display: block;
      width: 3px;
      height: 14px;
      background: #128df3;
      margin-right: 5px;
    }
  }
  .tableBox {
    padding-left: 40px;
  }
  .btnAddBox {
    padding: 10px 0;
    text-align: right;
  }
  .transfer {
    width: 600px;
    // max-height: 420px;
    // border: 1px solid red;
  }
}
</style>
<style lang="scss">
.dataSource {
  .transfer {
    .el-transfer-panel__body {
      height: 346px;
    }
    .el-transfer-panel__list {
      height: 300px;
    }
  }
}
</style>
